package org.groupg.practice.configuration.validator;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;

import java.util.ArrayList;
import java.util.List;

public class ValidatingConfigurationLoader {
    private final List<ConfigurationValidator> validators = new ArrayList<>();

    /**
     * 添加校验器
     */
    public void addValidator(ConfigurationValidator validator) {
        validators.add(validator);
    }

    /**
     * 加载配置并执行校验
     */
    public Configuration loadConfig(String configFile) throws ConfigurationException {
        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
                        .configure(params.properties().setFileName(configFile));

        PropertiesConfiguration config = builder.getConfiguration();

        // 执行所有校验器
        for (ConfigurationValidator validator : validators) {
            validator.validate(config);
        }

        return config;
    }
}